/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.config.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.dicenum.ApplyLevelNameEnum;
import com.icinfo.cloud.provider.common.dicenum.IsUseEnum;
import com.icinfo.cloud.provider.punish.config.dto.ConfigBusiParamMainDto;
import com.icinfo.cloud.provider.punish.config.dto.ConfigBusiParamMainPageRequest;
import com.icinfo.cloud.provider.punish.config.dto.ConfigBusiParamMainUseRequest;
import com.icinfo.cloud.provider.punish.config.dto.RelationWorkflowInfoRequest;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigBusiParamMainMapper;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamMain;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamMainService;
import com.icinfo.cloud.provider.punish.config.vo.ConfigBusiParamMainVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.workflow.config.service.IConfigWorkFlowDetailInfoService;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import com.icinfo.framework.tools.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 描述: 业务参数配置主表 config_busi_param_main 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年02月22日
 */
@Service
public class ConfigBusiParamMainServiceImpl extends MyBatisServiceSupport implements IConfigBusiParamMainService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(ConfigBusiParamMainServiceImpl.class);

    @Autowired
    private ConfigBusiParamMainMapper configBusiParamMainMapper;
    @Autowired
    private IConfigWorkFlowDetailInfoService configWorkFlowDetailInfoService;

    /**
     * 参数配置分页查询
     * @author liyafeng
     * @date 2022/2/22
      * @param request
     * @return {@link List< ConfigBusiParamMainVo>}
     */
    @Override
    public List<ConfigBusiParamMainVo> getConfigBusiParamMainVoList(ConfigBusiParamMainPageRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getLength(), request.getOrderBy());
        List<ConfigBusiParamMainVo> configBusiParamMainVos = configBusiParamMainMapper.selectConfigBusiParamMainVoList(request);
        for (ConfigBusiParamMainVo  configBusiParamMainVo:configBusiParamMainVos) {
            configBusiParamMainVo.setApplyLevelName(ApplyLevelNameEnum.getExplainByCode(configBusiParamMainVo.getApplyLevel()));
            configBusiParamMainVo.setIsUseName(IsUseEnum.getExplainByCode(configBusiParamMainVo.getIsUse()));
        }
        return configBusiParamMainVos;
    }
    /**
     * 保存参数配置
     * @author liyafeng
     * @date 2022/2/23
      * @param configBusiParamMainDto
     * @return {@link Result< String>}
     */
    @Override
    public Result<String> saveConfigBusiParamMainDto(ConfigBusiParamMainDto configBusiParamMainDto) {
        //判断使用级别+使用领域+使用区域是否已存在
        boolean isExist=checkIsExist(configBusiParamMainDto);
        if(isExist){
            return Result.error("已存在相同适用范围的配置项，请检查！");
        }
        ConfigBusiParamMain addConfigBusiParamMain=new ConfigBusiParamMain();
        BeanUtils.copyProperties(configBusiParamMainDto,addConfigBusiParamMain);
        List<String> applyAreaCodeList=configBusiParamMainDto.getApplyAreaCodeList();
        List<String> applyAreaNameList=configBusiParamMainDto.getApplyAreaNameList();
        List<String> applyFieldCodeList=configBusiParamMainDto.getApplyFieldCodeList();
        List<String> applyFieldNameList=configBusiParamMainDto.getApplyFieldNameList();
        String applyAreaCode=getFormData(applyAreaCodeList);
        String applyAreaName=getFormData(applyAreaNameList);
        String applyFieldCode=getFormData(applyFieldCodeList);
        String applyFieldName=getFormData(applyFieldNameList);
        addConfigBusiParamMain.setApplyAreaCode(applyAreaCode);
        addConfigBusiParamMain.setApplyAreaName(applyAreaName);
        addConfigBusiParamMain.setApplyFieldCode(applyFieldCode);
        addConfigBusiParamMain.setApplyFieldName(applyFieldName);
        addConfigBusiParamMain.setId(StringUtils.uuid());
        addConfigBusiParamMain.setCreateTime(new Date());
        //默认启用
        addConfigBusiParamMain.setIsUse("1");
        UserDTO userInfo = UserUtil.getUserInfo();
        if(userInfo==null){
            return Result.error("未登录或登录信息已失效");
        }
        addConfigBusiParamMain.setCreateUserId(userInfo.getUserId().toString());
        addConfigBusiParamMain.setCreateUserName(userInfo.getRealName());
        int addNum=configBusiParamMainMapper.insert(addConfigBusiParamMain);
        if(addNum>0){
            return Result.success("保存成功");
        }else {
            return Result.error("保存失败");
        }
    }
    /**
     * 校验 使用级别+使用领域+使用区域是否已存在
     * @author liyafeng
     * @date 2022/3/1
      * @param configBusiParamMainDto
     * @return {@link boolean}
     */
    private boolean checkIsExist(ConfigBusiParamMainDto configBusiParamMainDto) {
        boolean isExist=false;
        Map<String,Object> paramMap=new HashMap<>();
        paramMap.put("applyLevel",configBusiParamMainDto.getApplyLevel());
        paramMap.put("applyFieldType",configBusiParamMainDto.getApplyFieldType());
        paramMap.put("applyAreaType",configBusiParamMainDto.getApplyAreaType());
        paramMap.put("applyFieldCodeList",configBusiParamMainDto.getApplyFieldCodeList());
        paramMap.put("applyAreaCodeList",configBusiParamMainDto.getApplyAreaCodeList());
        List<ConfigBusiParamMain> configBusiParamMains=configBusiParamMainMapper.selectConfigBusiParamMainList(paramMap);
        if(null!=configBusiParamMains&&configBusiParamMains.size()>0){
            isExist=true;
        }
        return isExist;
    }


    /**
     * 拆分组装数据
     * @author liyafeng
     * @date 2022/3/1
     * @param list
     * @return {@link String}
     */
    public String getFormData(List<String> list) {
        String formStr="";
        if(null!=list&&list.size()>0) {
            for (String str : list) {
                if ("".equals(formStr)) {
                    formStr = str;
                } else {
                    formStr = formStr + ";" + str;
                }
            }
        }
        return formStr;
    }
    /**
     * 修改参数配置
     * @author liyafeng
     * @date 2022/2/23
      * @param configBusiParamMainDto
     * @return {@link Result< String>}
     */
    @Override
    public Result<String> editConfigBusiParamMain(ConfigBusiParamMainDto configBusiParamMainDto) {
        ConfigBusiParamMain updateConfigBusiParamMain=new ConfigBusiParamMain();
        BeanUtils.copyProperties(configBusiParamMainDto,updateConfigBusiParamMain);
        String applyAreaCode=getFormData(configBusiParamMainDto.getApplyAreaCodeList());
        String applyAreaName=getFormData(configBusiParamMainDto.getApplyAreaNameList());
        String applyFieldCode=getFormData(configBusiParamMainDto.getApplyFieldCodeList());
        String applyFieldName=getFormData(configBusiParamMainDto.getApplyFieldNameList());
        updateConfigBusiParamMain.setApplyFieldCode(applyFieldCode);
        updateConfigBusiParamMain.setApplyFieldName(applyFieldName);
        updateConfigBusiParamMain.setApplyAreaCode(applyAreaCode);
        updateConfigBusiParamMain.setApplyAreaName(applyAreaName);
        int editNum=configBusiParamMainMapper.updateByPrimaryKeySelective(updateConfigBusiParamMain);
        if(editNum>0){
            return Result.success("修改成功");
        }else {
            return Result.error("修改失败");
        }
    }
    /**
     * 修改启用状态
     * @author liyafeng
     * @date 2022/2/23
      * @param param
     * @return {@link Result< String>}
     */
    @Override
    public Result<String> editUse(ConfigBusiParamMainUseRequest param) {
        ConfigBusiParamMain updateConfigBusiParamMain=new ConfigBusiParamMain();
        updateConfigBusiParamMain.setIsUse(param.getIsUse());
        updateConfigBusiParamMain.setId(param.getId());
        int editNum=configBusiParamMainMapper.updateByPrimaryKeySelective(updateConfigBusiParamMain);
        if(editNum>0){
            return Result.success("修改启用状态成功");
        }else {
            return Result.error("修改启用状态失败");
        }
    }
    /**
     * 获取参数配置详情
     * @author liyafeng
     * @date 2022/2/23
      * @param id
     * @return {@link Result< ConfigBusiParamMain>}
     */
    @Override
    public Result<ConfigBusiParamMain> getDetail(String id) {
        ConfigBusiParamMain configBusiParamMain=configBusiParamMainMapper.selectByPrimaryKey(id);
        configBusiParamMain.setApplyAreaCodeList(strConverList(configBusiParamMain.getApplyAreaCode()));
        configBusiParamMain.setApplyAreaNameList(strConverList(configBusiParamMain.getApplyAreaName()));
        configBusiParamMain.setApplyFieldCodeList(strConverList(configBusiParamMain.getApplyFieldCode()));
        configBusiParamMain.setApplyFieldNameList(strConverList(configBusiParamMain.getApplyFieldName()));
        return Result.success(configBusiParamMain);
    }
    /**
     * 根据领域编码、区划编码获取工作流信息
     * @author liyafeng
     * @date 2022/3/5
     * @param
     */
    @Override
    public Map<String,Object> getRelationWorkflowInfo(RelationWorkflowInfoRequest request) {
        logger.info("==> 根据领域编码、区划编码，案件类型获取工作流信息：入参：{}", JSONUtil.toJsonStr(request));
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("success","false");
        resultMap.put("msg","未找到相关配置信息，请联系管理员处理！");
        //根据领域编码、区划编码获取参数配置信息
        List<ConfigBusiParamMain> configBusiParamMainList=getConfigBusiParamMainList(request);
        ConfigBusiParamMain configBusiParamMain=new ConfigBusiParamMain();
        if(null!=configBusiParamMainList&&configBusiParamMainList.size()>0){
            configBusiParamMain=configBusiParamMainList.get(0);
            String workflowCode = configBusiParamMain.getRelationWorkflowId();
            if (CaseTypeEnum.SIMPLE_QUICK.getCode().equals(request.getCaseType())) {
                //安吉速结
                workflowCode = configBusiParamMain.getRelationFastWorkflowId();
            } else if (CaseTypeEnum.FAST_PROCEDURE.getCode().equals(request.getCaseType())) {
                //简案快办
                workflowCode = configBusiParamMain.getRelationProvinceFastWorkflowId();
            }
            resultMap.put("success","true");
            resultMap.put("msg","获取工作流成功！");
            resultMap.put("WORKFLOWCODE",workflowCode);
        }
        return resultMap;
    }
    /**
     * 根据领域、区划获取
     * @author liyafeng
     * @date 2022/3/13
      * @param
     * @return {@link List< ConfigBusiParamMain>}
     */
    @Override
    public List<ConfigBusiParamMain> getConfigBusiParamMainList(RelationWorkflowInfoRequest request) {
        List<ConfigBusiParamMain> configBusiParamMainList=configBusiParamMainMapper.selectRelationWorkflowInfoId(request);
        if(null!=configBusiParamMainList&&configBusiParamMainList.size()>0){
            return configBusiParamMainList;
        }
        String areaCode=request.getApplyAreaCode();
        //若为地市 则查省级
        if(areaCode.endsWith("00000000")){
            //查省级
            String sAreaCode=areaCode.substring(0,2)+"00"+areaCode.substring(4,areaCode.length());
            RelationWorkflowInfoRequest relationWorkflowInfoRequest=new RelationWorkflowInfoRequest();
            relationWorkflowInfoRequest.setApplyAreaCode(sAreaCode);
            relationWorkflowInfoRequest.setApplyFieldCode(request.getApplyFieldCode());
            configBusiParamMainList=configBusiParamMainMapper.selectRelationWorkflowInfoId(relationWorkflowInfoRequest);
            if(null!=configBusiParamMainList&&configBusiParamMainList.size()>0){
                return configBusiParamMainList;
            }
        //若为区县 则查地市 省级
        }else if(areaCode.endsWith("000000")){
            //查地市
            String dAreaCode=areaCode.substring(0,4)+"00"+areaCode.substring(6,areaCode.length());
            RelationWorkflowInfoRequest relationWorkflowInfoRequest=new RelationWorkflowInfoRequest();
            relationWorkflowInfoRequest.setApplyAreaCode(dAreaCode);
            relationWorkflowInfoRequest.setApplyFieldCode(request.getApplyFieldCode());
            configBusiParamMainList=configBusiParamMainMapper.selectRelationWorkflowInfoId(relationWorkflowInfoRequest);
            if(null!=configBusiParamMainList&&configBusiParamMainList.size()>0){
                return configBusiParamMainList;
            }
            //查省级
            String sAreaCode=areaCode.substring(0,2)+"0000"+areaCode.substring(6,areaCode.length());
            RelationWorkflowInfoRequest sRelationWorkflowInfoRequest=new RelationWorkflowInfoRequest();
            sRelationWorkflowInfoRequest.setApplyAreaCode(sAreaCode);
            sRelationWorkflowInfoRequest.setApplyFieldCode(request.getApplyFieldCode());
            configBusiParamMainList=configBusiParamMainMapper.selectRelationWorkflowInfoId(sRelationWorkflowInfoRequest);
            if(null!=configBusiParamMainList&&configBusiParamMainList.size()>0){
                return configBusiParamMainList;
            }
        //街道乡镇 则查区县 地市 省级
        }else if(areaCode.endsWith("000")){
            //区县
            String qAreaCode=areaCode.substring(0,6)+"000"+areaCode.substring(9,areaCode.length());
            RelationWorkflowInfoRequest qRelationWorkflowInfoRequest=new RelationWorkflowInfoRequest();
            qRelationWorkflowInfoRequest.setApplyAreaCode(qAreaCode);
            qRelationWorkflowInfoRequest.setApplyFieldCode(request.getApplyFieldCode());
            configBusiParamMainList=configBusiParamMainMapper.selectRelationWorkflowInfoId(qRelationWorkflowInfoRequest);
            if(null!=configBusiParamMainList&&configBusiParamMainList.size()>0){
                return configBusiParamMainList;
            }
            //地市
            String dAreaCode=areaCode.substring(0,4)+"00000"+areaCode.substring(9,areaCode.length());
            RelationWorkflowInfoRequest dRelationWorkflowInfoRequest=new RelationWorkflowInfoRequest();
            dRelationWorkflowInfoRequest.setApplyAreaCode(dAreaCode);
            dRelationWorkflowInfoRequest.setApplyFieldCode(request.getApplyFieldCode());
            configBusiParamMainList=configBusiParamMainMapper.selectRelationWorkflowInfoId(dRelationWorkflowInfoRequest);
            if(null!=configBusiParamMainList&&configBusiParamMainList.size()>0){
                return configBusiParamMainList;
            }
            //省级
            String sAreaCode=areaCode.substring(0,2)+"0000000"+areaCode.substring(9,areaCode.length());
            RelationWorkflowInfoRequest sRelationWorkflowInfoRequest=new RelationWorkflowInfoRequest();
            sRelationWorkflowInfoRequest.setApplyAreaCode(sAreaCode);
            sRelationWorkflowInfoRequest.setApplyFieldCode(request.getApplyFieldCode());
            configBusiParamMainList=configBusiParamMainMapper.selectRelationWorkflowInfoId(sRelationWorkflowInfoRequest);
            if(null!=configBusiParamMainList&&configBusiParamMainList.size()>0){
                return configBusiParamMainList;
            }
        }
        configBusiParamMainList=configBusiParamMainMapper.selectAllFieldAndAllProvinceRelationWorkflowInfoId();
        return configBusiParamMainList;
    }

    /**
     * 字符串拆分转list
     * @author liyafeng
     * @date 2022/3/1
     * @param str
     * @return {@link List< String>}
     */
    private List<String> strConverList(String str) {
        List<String> strList=new ArrayList<>();
        if(StringUtils.isNotBlank(str)){
            String[] strArr = str.split(";");
            strList= Arrays.asList(strArr);
        }
        return strList;
    }
}
